package com.whjk.system.data.uitls;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.data.TextRenderData;
import com.deepoove.poi.data.style.Style;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.whjk.core.security.config.FileUploadConfig;
import com.whjk.system.data.annotation.DocParam;
import com.whjk.system.data.vo.SVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

@Component
public class DocTestUtil {

    private static String url;
    private static String templeUrl;

    @Autowired
    private FileUploadConfig fileUploadConfig;

    @PostConstruct
    private void getUrl() {
        url = fileUploadConfig.getUrl();
    }

    @PostConstruct
    private void getTempleUrl() {
        templeUrl = fileUploadConfig.getTempleUrl();
    }

    /**
     * 得到类的路径
     *
     * @return
     * @throws java.lang.Exception
     */
    public static String getClassPath() {
        String strClassName = DocTestUtil.class.getName();
        String strPackageName = DocTestUtil.class.getPackage() != null ? DocTestUtil.class.getPackage().getName() : "";
        String strClassFileName = strPackageName.isEmpty() ? strClassName : strClassName.substring(strPackageName.length() + 1);

        URL url = DocTestUtil.class.getResource(strClassFileName + ".class");
        String strURL = url.toString().substring(url.toString().indexOf('/') + 1, url.toString().lastIndexOf('/'));

        return strURL.replaceAll("%20", " ");
    }

    public static String readWord(String inPath, SVo arrList) throws Exception {
        String property = System.getProperty("user.dir");
        String rootPath = property.substring(0, property.indexOf(":") + 1);
        String basePath = rootPath + url;
        String s = basePath + inPath;
        File file2 = new File(s);
        if (!file2.exists()) {
            throw new RuntimeException(inPath + "文件不存在!!!");
        }
        Resource resource = new FileSystemResource(s);
        String templateFileName = resource.getFilename();

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss-SSS");
        String fileName = fmt.format(now) + "-" + templateFileName;
        String path = templateFileName.substring(0, templateFileName.lastIndexOf("."));
        //生成的新文件地址
        String filePath = basePath + templeUrl + "/pdf/" + path + "/" + fileName;
        //创建的新文件地址
        File directory = new File(basePath + templeUrl + "/pdf/" + path);
        if (!directory.exists()) {
            boolean created = directory.mkdirs();
            if (!created) {
                throw new Exception("无法创建目录: " + directory.getAbsolutePath());
            }
        } else {
            //如果存在清空文件夹
            for (File file : Objects.requireNonNull(directory.listFiles())) {
                if (!file.isDirectory()) {
                    file.delete();
                }
            }
        }
        Configure analysis = analysis(arrList);

        XWPFTemplate template = XWPFTemplate.compile(s, analysis).render(arrList);
        OutputStream outputStreamTemplate = Files.newOutputStream(Paths.get(filePath));
        //写入之前先清空该文件夹


        template.write(outputStreamTemplate);

        // 关闭资源
        template.close();
        outputStreamTemplate.close();

        System.out.println(filePath);
        return templeUrl + "/pdf/" + path + "/" + fileName;
    }

    /**
     * 解析
     */
    public static Configure analysis(SVo sVo) throws Exception {
        Class<? extends SVo> aClass = sVo.getClass();
        Field[] fields = aClass.getDeclaredFields();
        Configure config = Configure.builder().build();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.get(sVo) == null) {
                continue; // 跳过处理null值的字段
            }
            if (field.isAnnotationPresent(DocParam.class)) {
                DocParam columnConfig = field.getAnnotation(DocParam.class);
                int code = columnConfig.type().code;
                String value = field.get(sVo).toString();
                if (StringUtils.isNotBlank(value)) {
                    if (code == 1) {
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(columnConfig.textColor())) {
                            Style style = new Style();
                            style.setColor(columnConfig.textColor());
                            TextRenderData textRenderData = new TextRenderData();
                            textRenderData.setText(value);
                            textRenderData.setStyle(style);
                            field.set(sVo, textRenderData);
                        }
                    }
                    if (code == 2) {
                        BufferedImage bufferedImage = BASE64DecodedMultipartFile.base64ToBufferedImage(value);
                        if (bufferedImage != null) {
                            // java图片
                            field.set(sVo, Pictures.ofBufferedImage(bufferedImage, columnConfig.imgType()).size(columnConfig.imgSize()[0], columnConfig.imgSize()[1]).create());
                        }
                    }
                    if (code == 3) {
                        String classPath = getClassPath();
                        String imgPath = classPath.split(":")[0] + ":" + url + value.replace("/tempFileUrl/", "/");
                        File file = new File(imgPath);
                        if (file.exists()) {
                            // 图片流
                            field.set(sVo, Pictures.ofStream(Files.newInputStream(Paths.get(imgPath)), columnConfig.imgType()).size(columnConfig.imgSize()[0], columnConfig.imgSize()[1]).create());
                        }
                    }
                }
            }
            if (field.getType().equals(List.class)) {
                LoopRowTableRenderPolicy renderPolicy = new LoopRowTableRenderPolicy();
                config.customPolicy(field.getName(), renderPolicy);
            }
        }
        return config;
    }
}